<?php


namespace app\api\service;


use app\api\model\Language;
use app\api\model\Teacher;
use app\api\model\TeacherCourse;
use think\Db;

class SearchService
{
    /**
     * 搜索
     * @param string $searchName 搜索名称
     * @param array $data 筛选条件
     */
    public static function search($data)
    {
        $where = self::teacherCourseWhere($data);
        $orderBy = self::orderBy($data['order_by'] ?? '');
        $fields = self::fields();
        //距离排序
        if (isset($data['order_by']) && $data['order_by'] == 'distance') {
            $longitude = $data['longitude'] ?? 113.317339;
            $latitude = $data['latitude'] ?? 23.095207;
            $fields = $fields.self::distanceField($longitude, $latitude);
            $orderBy = 'distance asc';
        }
        return self::table($fields, $where, $orderBy, $data['size']);
    }

    /**
     * 连表
     */
    private static function table($fields, $where, $orderBy, $size = 20)
    {
        return TeacherCourse::with(['teacher' => function ($query) {
            $query->with('tag');
        }, 'language', 'grade'])
            ->withCount('course')
            ->field($fields)
            ->join('teacher t', 'teacher_course.teacher_id = t.teacher_id')
            ->where($where)
            ->order($orderBy)
            ->paginate($size);
    }

    private static function fields()
    {
        return 'teacher_course.*, t.teacher_id, t.longitude, t.latitude';
    }

    private static function distanceField($longitude, $latitude)
    {
        return ', ROUND(
            6378.138 * 2 * ASIN(
                SQRT(
                    POW(
                        SIN(
                            (
                                '.$latitude.' * PI() / 180 - latitude * PI() / 180
                            ) / 2
                        ),
                        2
                    ) + COS('.$latitude.' * PI() / 180) * COS(latitude * PI() / 180) * POW(
                        SIN(
                            (
                                '.$longitude.' * PI() / 180 -   longitude * PI() / 180
                            ) / 2
                        ),
                        2
                    )
                )
            ) * 1000
        ) AS distance';
    }

    /**
     * 语种ID
     */
    public static function languageId($serchName)
    {
        return Language::where('title', 'like', "%{$serchName}%")->column('language_id');
    }

    /**
     * 教师ID
     */
    public static function teacherId($serchName)
    {
        return Teacher::where('nickname', 'like', "%{$serchName}%")->column('teacher_id');
    }

    /**
     * 课程条件
     */
    public static function teacherCourseWhere($data)
    {
        $where = [
            'onlineswitch' => 1
        ];
        //教师ID
        $teacherId = self::teacherId($data['search_name']);
        if ($teacherId) {
            $where['t.teacher_id'] = ['in', $teacherId];
        }
        //语种ID
        $languageId = self::languageId($data['search_name']);
        if ($languageId) {
            $where['language_id'] = ['in', $languageId];
        }
        if (!$teacherId && !$languageId) {
            $where['t.teacher_id'] = ['in', $teacherId];
            $where['t.teacher_id'] = ['in', $teacherId];
        }
        //是否职业
        if (isset($data['profession']) && $data['profession']) {
            $where['t.profession'] = ['=', $data['profession']];
        }
        //性别
        if (isset($data['sex']) && $data['sex']) {
            $where['t.sex'] = ['=', $data['sex']];
        }
        //教学经验
        if (isset($data['teaching_year']) && $data['teaching_year']) {
            $year = date('Y') - $data['teaching_year'];
            $where['year'] = [['>', 0], ['<=', $year]];
        }

        //价格区间
        $minPrice = 0;
        if (isset($data['min_price']) && $data['min_price']) {
            $minPrice = $data['min_price'];
            $where['price'] = ['>=', $minPrice];
        }
        if (isset($data['max_price']) && $data['max_price']) {
            $where['price'] = ['between', [$minPrice, $data['max_price']]];
        }
        //等级
        if (isset($data['grade']) && $data['grade']) {
            $where['language_grade_id'] = ['in', $data['grade']];
        }
        return $where;
    }

    /**
     * 评分、授课排序
     */
    private static function orderBy($order)
    {
        $orderBy = 'weigh desc';
        if ($order == 'score') {
            $orderBy = 'score desc';
        }
        if ($order == 'finish') {
            $orderBy = 'finish desc';
        }
        return $orderBy;
    }




}